package com.yihuier.yihuier.Service.Common;

import com.yihuier.yihuier.Entity.MeetingManager.MeetingData;
import com.yihuier.yihuier.Mapper.Common.FileUploadMapper;
import com.yihuier.yihuier.Util.ByteOperator;
import com.yihuier.yihuier.Util.GeneralHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

@Service
public class FileUploadService {

    @Autowired
    private FileUploadMapper fileUploadMapper;


    public boolean updateUserHeaderPic(int id,String user_header_pic){
        if (fileUploadMapper.setUserHeaderPic(id,user_header_pic) > 0){
            return true;
        }
        return false;
    }

    public boolean updateRoomPic(int id,String room_pic){
        if (fileUploadMapper.setRoomPic(id,room_pic) > 0 ){
            return true;
        }
        return false;
    }

    public boolean uploadMeetingFile(MeetingData data){
        if (fileUploadMapper.addMeetingData(data.getData_meeting_id(),data.getData_name(),data.getData_type(),data.getData_address()) > 0 ){
            return true;
        }
        return false;
    }

    /**
     * 判断文件是否存在
     * @param dir 目标文件目录
     * @param filename 文件名称
     * @return 存在则true，不存在则false
     */
    public boolean findFileIsExist(Path dir, String filename){
        return Files.exists(dir.resolve(filename));
    }

    /**
     * 获取文件名称，通过MD5算法HASH出文件的MD5值，作为文件名
     * @param in 文件的输入流
     * @return 文件名字
     */
    public String getFileName(InputStream in){
        GeneralHash hashTool = new GeneralHash(GeneralHash.HashMode.MD5);

        return ByteOperator.encodeHex(hashTool.Hash(in));
    }
}
